﻿// <copyright file="TaskProviders.cs">
// Copyright (c) Chad Weimer
// </copyright>
// <author>Chad Weimer</author>
// <summary>
// This file is part of Tasx.
//
// Tasx is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Tasx is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Tasx.  If not, see http://www.gnu.org/licenses/.
// </summary>

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Reflection;

using System.Diagnostics;

namespace Tasx.Definitions
{
	/// <summary>
	/// Helper class for retrieving a <see cref="ITaskProvider"/>.
	/// </summary>
	public class TaskProviders
	{	
		[ImportMany]
		private IEnumerable<Lazy<ITaskProvider, ITaskProviderData>> _providers;
		
		static TaskProviders()
		{
			Providers = new TaskProviders();
		}
		
		protected TaskProviders()
		{
			try
			{
				var catalog = new AggregateCatalog();
				catalog.Catalogs.Add(new DirectoryCatalog(@".\providers\", "*.Providers.*.dll"));
				var container = new CompositionContainer(catalog);
				container.ComposeParts(this);
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex.Message);
			}
		}
		
		public static TaskProviders Providers { get; protected set; }
		
		/// <summary>
		/// Find a loaded <see cref="ITaskProvider"/> by name.
		/// </summary>
		/// <param name="name">The name of the provider.</param>
		/// <returns>The <see cref="ITaskProvider"/> with the specified name, or <c>null</c> if none was found.</returns>
		public ITaskProvider FindByName(string name)
		{
			if(_providers != null)
			{
				foreach(var provider in _providers)
				{
					if(provider.Metadata.Name == name)
					{
						return provider.Value;
					}
				}
			}
			
			return null;
		}
		
		public IEnumerable<string> GetAvailableProviders()
		{
			foreach(var provider in _providers)
			{
				yield return provider.Metadata.Name;
			}
		}
	}
}
